package com.application.attachment.struts.actions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;

import com.application.attachment.commons.Constants;
import com.application.attachment.entity.Attachment;
import com.application.attachment.service.AttachmentService;
import com.application.attachment.struts.form.AttachmentForm;
import com.application.transitiondownlog.entity.Transitiondownlog;
import com.application.transitiondownlog.service.TransitiondownlogService;
import com.application.yfplacefiledownlog.entity.YfPlacefiledownlog;
import com.application.yfplacefiledownlog.service.YfPlacefiledownlogService;
import com.manager.commons.CommonUtil;
import com.manager.commons.RandomKey;
import com.manager.commons.page.PageBean;

public class AttachmentAction extends DispatchAction {

	/**
	 * Service层实例
	 */
	private AttachmentService attachmentService;

	/**
	 * 日志
	 */
	private Logger log = Logger.getLogger(this.getClass());

	/**
	 * 实体对象
	 */
	private Attachment attachment;
	
	private YfPlacefiledownlogService yfPlacefiledownlogService;
	
	private TransitiondownlogService transitiondownlogService;
	



	/**
	 * 采用partialList方式分页程序
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public ActionForward getAttachmentPartialList(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.debug("searchAttachment" + "开始");
		AttachmentForm attachment = (AttachmentForm) form;
		// 统计总记录数的sql语句
		int resultSize = 0;
		// 初始化pageBean供分页所用
		PageBean pageBean = null;
		// 取得当前页list数据
		List attachmentList = null;
		resultSize = attachmentService.getAllCountAttachment(attachment);
		pageBean = PageBean.getPageBean("attachmentTab", resultSize, request);
		attachmentList = attachmentService.searchAttachment(attachment, pageBean);
		request.setAttribute("attachmentList", attachmentList);

		log.debug("searchAttachment" + "结束");

		return mapping.findForward(Constants.SUCCESS);
	}

	/**
	 * 到达新增页面
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * @throws Exception
	 */
	public ActionForward toAddAttachment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug("toAddAttachments");
		return mapping.findForward(Constants.SUCCESS);
	}

	/**
	 * 增加
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * @throws Exception
	 */
	public ActionForward addAttachment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug("addAttachments");
		Attachment attachment = this.getAttachment(form);
		this.attachmentService.insertObject(attachment);

		return mapping.findForward(Constants.SUCCESS);
	}

	/**
	 * 删除
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * @throws Exception
	 */
	public ActionForward deleteAttachment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug("deleteAttachments");
		AttachmentForm attachmentForm = (AttachmentForm) form;
		String fid = attachmentForm.getFid();
		String type = attachmentForm.getType();
		if(StringUtils.isBlank(fid)){
			fid = request.getParameter("fid");
		}
		if(StringUtils.isBlank(type)){
			type = request.getParameter("type");
		}
		Attachment attachment = this.getAttachment(form);
		attachment = this.attachmentService.getAttachment(attachment);
		String serverPath=CommonUtil.ATTACHE_FILE;
		if(StringUtils.isBlank(serverPath)){
			serverPath=request.getSession().getServletContext().getRealPath("/"); 
		}
		String url = attachment.getUrl();
		String fileName = attachment.getFilename();
		attachmentForm.setIds(attachmentForm.getId().toString());
		attachmentForm.setFid(null);
		attachmentForm.setType(null);
		this.attachmentService.deleteAttachments(attachmentForm);
		File file = new File(serverPath + url);
        file.delete();
    	url = "/queryAttachment.do?method=queryAttachment&fid=" + fid + "&type=" + type;
		ActionForward forward = new ActionForward(url);
		return forward;
	}

	
	/**
	 * 删除
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * @throws Exception
	 */
	public ActionForward deletePlaceFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug("deletePlaceFile");
		AttachmentForm attachmentForm = (AttachmentForm) form;
		String fid = attachmentForm.getFid();
		String type = attachmentForm.getType();
		String bussName = attachmentForm.getBussName();
		if(StringUtils.isBlank(fid)){
			fid = request.getParameter("fid");
		}
		if(StringUtils.isBlank(type)){
			type = request.getParameter("type");
		}
		if(StringUtils.isBlank(bussName)){
			bussName = request.getParameter("bussName");
		}
		Attachment attachment = this.getAttachment(form);
		attachment = this.attachmentService.getAttachment(attachment);
		String serverPath=CommonUtil.ATTACHE_FILE;
		if(StringUtils.isBlank(serverPath)){
			serverPath=request.getSession().getServletContext().getRealPath("/"); 
		}
		String url = attachment.getUrl();
		String fileName = attachment.getFilename();
		attachmentForm.setIds(attachmentForm.getId().toString());
		attachmentForm.setFid(null);
		attachmentForm.setType(null);
		this.attachmentService.deleteAttachments(attachmentForm);
		File file = new File(serverPath + url);
        file.delete();
        
    	int num = attachmentService.getFileNumCount(bussName);
		num = num - 1;
		if(num<0){
			num = 0;
		}
		attachmentService.updateFileNum(bussName, Long.valueOf(num));
        url = "/viewYfPlacefile.do?method=viewYfPlacefile&id=" + bussName;
		ActionForward forward = new ActionForward(url);
		return forward;
	}
	/**
	 * 删除
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * @throws Exception
	 */
	public ActionForward deleteCph(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug("deleteCph");
		AttachmentForm attachmentForm = (AttachmentForm) form;
		String fid = attachmentForm.getFid();
		String type = attachmentForm.getType();
		String bussName = attachmentForm.getBussName();
		if(StringUtils.isBlank(fid)){
			fid = request.getParameter("fid");
		}
		if(StringUtils.isBlank(type)){
			type = request.getParameter("type");
		}
		if(StringUtils.isBlank(bussName)){
			bussName = request.getParameter("bussName");
		}
		Attachment attachment = this.getAttachment(form);
		attachment = this.attachmentService.getAttachment(attachment);
		String serverPath=CommonUtil.ATTACHE_FILE;
		if(StringUtils.isBlank(serverPath)){
			serverPath=request.getSession().getServletContext().getRealPath("/"); 
		}
		String url = attachment.getUrl();
		String fileName = attachment.getFilename();
		attachmentForm.setIds(attachmentForm.getId().toString());
		attachmentForm.setFid(null);
		attachmentForm.setType(null);
		this.attachmentService.deleteAttachments(attachmentForm);
		File file = new File(serverPath + url);
        file.delete();
        url = "/viewTransition.do?method=viewTransition&id=" + bussName;
		ActionForward forward = new ActionForward(url);
		return forward;
	}
	
	/**
	 * 到达更新页面
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * @throws Exception
	 */
	public ActionForward toUpdateAttachment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug("toUpdateAttachments");

		Attachment attachment = this.getAttachment(form);
		attachment = this.attachmentService.getAttachment(attachment);
		request.setAttribute(Constants.ATTACHMENT, attachment);
		return mapping.findForward(Constants.SUCCESS);
	}

	/**
	 * 更新
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * @throws Exception
	 */
	public ActionForward updateAttachment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug("updateAttachments");
		Attachment attachment = this.getAttachment(form);
		this.attachmentService.updateObject(attachment);

		return mapping.findForward(Constants.SUCCESS);
	}

	/**
	 * 查看页面
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * @throws Exception
	 */
	public ActionForward viewAttachment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug("viewAttachment");

		Attachment attachment = this.getAttachment(form);
		attachment = this.attachmentService.getAttachment(attachment);
		request.setAttribute(Constants.ATTACHMENT, attachment);
		return mapping.findForward(Constants.SUCCESS);
	}

	protected String saveFile(FormFile formFile,HttpServletRequest request) throws Exception
	{
		
		String serverPath=CommonUtil.ATTACHE_FILE;
		if(StringUtils.isBlank(serverPath)){
			serverPath=request.getSession().getServletContext().getRealPath("/"); 
		}else{
			File attachFile = new File(serverPath + "upload\\");
			if(!attachFile.exists()){
				attachFile.mkdirs();
			}
		}
		String fileName = formFile.getFileName();
		String suffix = fileName.substring(fileName.indexOf("."));
		String url =  "upload\\" +  fileName.substring(0,fileName.indexOf(".")) + "_" + getRadomFileName() + suffix;
		InputStream in = formFile.getInputStream(); 
		FileOutputStream fout = new FileOutputStream(serverPath + url);
		byte buffer[] = new byte[8192];
		int count = 0;
		// 开始向上传路径中刚建立的文件写入数据，每次写8k字节
		while ((count = in.read(buffer)) > 0)
		{
			fout.write(buffer, 0, count);
		}
		fout.close();
		formFile.destroy(); 
		return url;
	}
    
	/**
	 * 
	* 上传附件
	* @param mapping
	* @param form
	* @param request
	* @param response
	* @return
	* @throws Exception
	 */
	public ActionForward uploadAttachment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug("uploadAttachment");
		AttachmentForm attachmentForm = (AttachmentForm) form;
		String fid = "";
		String type = "";
		fid = StringUtils.isBlank(attachmentForm.getFid())?RandomKey.generateID_String_19():attachmentForm.getFid();
		type = attachmentForm.getType();
		if(attachmentForm.getFormFile()==null){
			String message = "单个附件大小不能超过10M";
            request.setAttribute("message",message);
            String url = "/queryAttachment.do?method=queryAttachment&fid=" + fid + "&type=" + type;
    		ActionForward forward = new ActionForward(url);
            return forward;
		}
		if(attachmentForm.getFormFile().getFileSize() > Constants.ATTACHMENT_SIZE){
			String message = "单个附件大小不能超过10M";
            request.setAttribute("message",message);
			
		}else{
			try
			{
				String path = saveFile(attachmentForm.getFormFile(),request);
				attachment = new Attachment();
				attachment.setFid(fid);
				attachment.setType(type);
				attachment.setUrl(path);
				attachment.setFilename(attachmentForm.getFormFile().getFileName());
				attachment.setInputtime(new Date());
				attachment.setBak1(attachmentForm.getBak1());
				attachment.setBak3(attachmentForm.getBak3());
				attachment.setOperateid(CommonUtil.getCurrentUser(request).getId());
				attachmentService.insertObject(attachment);
			}
			catch(Exception e)
			{
				log.debug(e.getMessage());
			}
		}
		String url = "/queryAttachment.do?method=queryAttachment&fid=" + fid + "&type=" + type;
		ActionForward forward = new ActionForward(url);
		return forward;
	}
	
	
	
	
	
	public ActionForward placeFileUpload(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug("placeFileUpload");
		AttachmentForm attachmentForm = (AttachmentForm) form;
		String fid = "";
		String type = "";
		fid = StringUtils.isBlank(attachmentForm.getFid())?RandomKey.generateID_String_19():attachmentForm.getFid();
		type = attachmentForm.getType();
		String url = "/viewYfPlacefile.do?method=viewYfPlacefile&id=" + fid;
		if(request.getParameter("lx")!=null&&request.getParameter("lx").equals("cph")){
			url = "/viewTransition.do?method=viewTransition&id=" + fid;
		}
		if(attachmentForm.getFormFile()==null){
			String message = "单个附件大小不能超过10M";
            request.setAttribute("message",message);
    		ActionForward forward = new ActionForward(url);
            return forward;
		}
		if(attachmentForm.getFormFile().getFileSize() > Constants.ATTACHMENT_SIZE){
			String message = "单个附件大小不能超过10M";
            request.setAttribute("message",message);
			
		}else{
			try
			{
				String path = saveFile(attachmentForm.getFormFile(),request);
				attachment = new Attachment();
				attachment.setFid(fid);
				attachment.setType(type);
				attachment.setUrl(path);
				attachment.setFilename(attachmentForm.getFormFile().getFileName());
				attachment.setInputtime(new Date());
				attachment.setBak1(attachmentForm.getBak1());
				attachment.setBak3(attachmentForm.getBak3());
				attachment.setOperateid(CommonUtil.getCurrentUser(request).getId());
				attachmentService.insertObject(attachment);
				int num = attachmentService.getFileNumCount(fid);
				num = num + 1;
				attachmentService.updateFileNum(fid, Long.valueOf(num));
			}
			catch(Exception e)
			{
				log.debug(e.getMessage());
			}
		}
		ActionForward forward = new ActionForward(url);
		return forward;
	}
	
	
	
    
	public ActionForward queryAttachment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug("queryAttachment" + "开始");
		AttachmentForm attachmentForm = (AttachmentForm) form;
		List attachmentList = attachmentList = attachmentService.queryAttachment(attachmentForm);
		request.setAttribute("attachmentList", attachmentList);
		log.debug("queryAttachment" + "结束");
		return mapping.findForward(Constants.SUCCESS);
	} 
	
	public ActionForward placeFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug("placeFile" + "开始");
		AttachmentForm attachmentForm = (AttachmentForm)form;
		List attachmentList = attachmentList = attachmentService.queryAttachment(attachmentForm);
		request.setAttribute("attachmentList", attachmentList);
		log.debug("placeFile" + "结束");
		return mapping.findForward(Constants.SUCCESS);
	} 
	
	
	/**
	 * 
	* 下载附件
	*  
	* @param mapping
	* @param form
	* @param request
	* @param response
	* @return
	* @throws Exception
	 */
	public ActionForward downAttachment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug("downAttachment" + "开始");
		Attachment attachment = this.getAttachment(form);
		attachment = this.attachmentService.getAttachment(attachment);
		String serverPath=CommonUtil.ATTACHE_FILE;
		if(StringUtils.isBlank(serverPath)){
			serverPath=request.getSession().getServletContext().getRealPath("/"); 
		}
		String url = attachment.getUrl();
		String fileName = attachment.getFilename();
		try
		{
			download(serverPath + url,fileName, response);

		}
		catch(Exception e)
		{
			log.error("下载附件失败！", e);
		}
		return null;
	} 
	

	
	public ActionForward downPlaceFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug("downPlaceFile" + "开始");
		Attachment attachment = this.getAttachment(form);
		attachment = this.attachmentService.getAttachment(attachment);
		String serverPath=CommonUtil.ATTACHE_FILE;
		if(StringUtils.isBlank(serverPath)){
			serverPath=request.getSession().getServletContext().getRealPath("/"); 
		}
		String url = attachment.getUrl();
		String fileName = attachment.getFilename();
		try
		{
			download(serverPath + url,fileName, response);
			Date date = new Date();
			YfPlacefiledownlog downLog = new YfPlacefiledownlog();
			downLog.setId(RandomKey.generateID_Long_19());
			downLog.setDownPerson(CommonUtil.getCurrentUser(request).getRname());
			downLog.setDownTime(date);
			downLog.setFileName(attachment.getFilename());
		    String fileType = CommonUtil.getDictValue(Integer.parseInt(attachment.getType()), "FILE_TYPE");
			downLog.setFileType(fileType);
			downLog.setRemark(attachment.getBak3());
			downLog.setProjectNo(attachment.getBak1());
			downLog.setOperateid(CommonUtil.getCurrentUser(request).getId());
			downLog.setCreateDate(date);
			downLog.setPlaceId(attachment.getFid());
			yfPlacefiledownlogService.insertObject(downLog);
		}
		catch(Exception e)
		{
			log.error("下载附件失败！", e);
		}
		return null;
	} 
	
	public ActionForward downCPH(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug("downPlaceFile" + "开始");
		Attachment attachment = this.getAttachment(form);
		attachment = this.attachmentService.getAttachment(attachment);
		String serverPath=CommonUtil.ATTACHE_FILE;
		if(StringUtils.isBlank(serverPath)){
			serverPath=request.getSession().getServletContext().getRealPath("/"); 
		}
		String url = attachment.getUrl();
		String fileName = attachment.getFilename();
		try
		{
			download(serverPath + url,fileName, response);
			Date date = new Date();
			Transitiondownlog downLog = new Transitiondownlog();
			downLog.setId(RandomKey.generateID_Long_19());
			downLog.setDownPerson(CommonUtil.getCurrentUser(request).getRname());
			downLog.setDownTime(date);
			downLog.setFileName(attachment.getFilename());
		    String fileType = CommonUtil.getDictValue(Integer.parseInt(attachment.getType()), "FILE_TYPE");
			downLog.setFileType(fileType);
			downLog.setRemark(attachment.getBak3());
			downLog.setProjectNo(attachment.getBak1());
			downLog.setOperateid(CommonUtil.getCurrentUser(request).getId());
			downLog.setCreateDate(date);
			downLog.setPlaceId(attachment.getFid());
			transitiondownlogService.insertObject(downLog);
		}
		catch(Exception e)
		{
			log.error("下载附件失败！", e);
		}
		return null;
	} 
	
	
	public String getRadomFileName()
	{
		long time = System.currentTimeMillis();
		String fileName = "";
		Random rnd = new Random(); 
		String rndNum = String.valueOf(rnd.nextInt(10000));
		Date d = new Date(time);
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
		fileName = sf.format(d) + rndNum;
		return fileName;
	}
	
	public HttpServletResponse download(String filePath, String showName, HttpServletResponse response) throws Exception
	{
		FileInputStream fileIn = null;
		try
		{
			File file = new File(filePath);
			fileIn = new FileInputStream(file);
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			String fileName = "";
			if (!"".equals(showName) && null != showName)
			{
				fileName = new String(showName.getBytes("GBK"), "ISO8859_1");
			}
			else
			{
				fileName = new String(file.getName().getBytes("GBK"), "ISO8859_1");
			}
			response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
			byte[] b = new byte[32768];
			int len;
			while ((len = fileIn.read(b)) > 0)
			{
				response.getOutputStream().write(b, 0, len);
			}
			response.getOutputStream().flush();
			response.getOutputStream().close();
		}
		catch(FileNotFoundException ex)
		{
			log.error("file not found:" + filePath, ex);
			throw ex;
		}
		catch(IOException e)
		{
			log.error("download file error", e);
			throw e;
		}
		finally
		{
			try
			{
				if (fileIn != null)
				{
					fileIn.close();
				}
			}
			catch(IOException e)
			{
				log.error("下载时发生异常", e);
			}

		}
		return response;
	}
	
	
	
	
	
	

	// get--set
	/**
	 * @return the AttachmentService
	 */
	public AttachmentService getAttachmentService() {
		return this.attachmentService;
	}

	/**
	 * @param AttachmentService
	 *        the AttachmentService to set
	 */
	public void setAttachmentService(AttachmentService attachmentService) {
		this.attachmentService = attachmentService;
	}

	/**
	 * 获取Attachment实体
	 * 
	 * @param ActionForm
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @return the Attachment
	 */
	public Attachment getAttachment(ActionForm form) throws IllegalAccessException, InvocationTargetException {
		AttachmentForm attachmentForm = (AttachmentForm) form;
		attachment = new Attachment();
		BeanUtils.copyProperties(attachment, attachmentForm);
		return attachment;
	}

	public void setAttachment(Attachment attachment) {
		this.attachment = attachment;
	}
	
	public YfPlacefiledownlogService getYfPlacefiledownlogService() {
		return yfPlacefiledownlogService;
	}

	public void setYfPlacefiledownlogService(
			YfPlacefiledownlogService yfPlacefiledownlogService) {
		this.yfPlacefiledownlogService = yfPlacefiledownlogService;
	}

	/**
	 * @return the transitiondownlogService
	 */
	public TransitiondownlogService getTransitiondownlogService() {
		return transitiondownlogService;
	}

	/**
	 * @param transitiondownlogService the transitiondownlogService to set
	 */
	public void setTransitiondownlogService(
			TransitiondownlogService transitiondownlogService) {
		this.transitiondownlogService = transitiondownlogService;
	}

}
